import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import legacy from '@vitejs/plugin-legacy'
import { resolve } from 'path'
import fs from 'fs'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')

  // 从环境变量获取基础路径，默认为 'dist'
  const basePath = 'dist/' + env.VITE_BASE_PATH || 'dist'

  return {
    base: './',
    server: {
      host: '0.0.0.0',
    },
    // 开发模式和构建模式都使用相同的入口文件
    root: resolve(__dirname, 'src/pages/' + env.VITE_BASE_PATH),
    plugins: [
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      vue(),
      vueDevTools(),
      legacy({
        targets: ['defaults', 'not IE 11'],
      }),
    ],
    build: {
      target: ['es2015', 'chrome63'],
      outDir: resolve(__dirname, basePath), // 使用环境变量设置输出目录
      rollupOptions: {
        input: resolve(__dirname, 'src/pages/' + env.VITE_BASE_PATH + '/index.html'),
        plugins: [
          {
            name: 'move-html-to-root',
            async writeBundle(options, bundle) {
              // 在文件写入后移动HTML文件到根目录并清理src目录
              const { default: fs } = await import('fs')
              const { default: path } = await import('path')

              Object.keys(bundle).forEach((fileName) => {
                if (fileName.endsWith('.html') && fileName.includes('/')) {
                  const oldPath = path.join(options.dir, fileName)
                  const newPath = path.join(options.dir, 'index.html')

                  if (fs.existsSync(oldPath)) {
                    fs.renameSync(oldPath, newPath)
                  }
                }
              })

              // 删除整个src目录
              const srcDir = path.join(options.dir, 'src')
              if (fs.existsSync(srcDir)) {
                try {
                  fs.rmSync(srcDir, { recursive: true, force: true })
                } catch (e) {
                  console.warn('Failed to remove src directory:', e.message)
                }
              }
            },
          },
        ],
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
  }
})
